package com.steve.combat.algorithm.douyin;

import java.util.Arrays;
import java.util.Random;

/**
 * @Author: STEVE
 * @Description: 给10人随机分配100元红包，每人最低获取1元
 * @since: 2025-04-21
 */
public class RedPacket {

    public static int[] allocate(int totalAmount, int numPeople, int minAmount) {
        if (totalAmount < numPeople * minAmount) {
            throw new IllegalArgumentException("总金额不足以满足每人最低金额");
        }
        int remaining = totalAmount - numPeople * minAmount;
        int[] dividers = new int[numPeople - 1];
        Random random = new Random();

        // 生成numPeople - 1个随机隔板
        for (int i = 0; i < dividers.length; i++) {
            dividers[i] = random.nextInt(remaining + 1);
        }

        Arrays.sort(dividers);

        // 计算每个人的分配金额
        int[] result = new int[numPeople];
        int prev = 0;
        for (int i = 0; i < dividers.length; i++) {
            result[i] = dividers[i] - prev + minAmount;
            prev = dividers[i];
        }
        result[numPeople - 1] = remaining - prev + minAmount;
        return result;
    }

    public static void main(String[] args) {
        int[] amounts = allocate(100, 10, 1);
        System.out.println("分配结果：" + Arrays.toString(amounts));
        System.out.println("总和：" + Arrays.stream(amounts).sum()); // 验证总和
    }

}
